package com.haierp.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.haierp.model.Device;
import com.haierp.model.WxSession;
import com.haierp.model.WxUser;
import com.haierp.service.IDeviceService;
import com.haierp.service.IWxSessionService;
import com.haierp.service.IWxUserService;
import com.haierp.util.HttpClientUtil;
import com.haierp.util.JsonResult;
import com.haierp.util.Md5Util;
import com.haierp.util.PropertiesUtils;
import com.haierp.vo.UploadUserInfo;
import com.haierp.vo.WxModel;
import com.haierp.vo.WxRowData;
import com.haierp.vo.WxSystemInfo;
import com.haierp.vo.WxUserVO;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

import net.sf.json.JSONObject;


@Controller
@RequestMapping("/wx")
public class WxLoginController extends BaseController {

	
	@Autowired
	private IDeviceService deviceService;
	
	@Autowired
	private IWxSessionService wxSessionService;
	
	@Autowired
	private IWxUserService wxUserService;
	
	/**
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Object login(WxModel wxModel ) {
		JsonResult<String> result = new JsonResult<>();
		Map<String,WxSession> maps = wxSessionService.getMaps();
//		System.out.println(wxModel);
		Device device = null;
		if("login".equals(wxModel.getOp())){
			//1解析JSON
			String systemInfo = wxModel.getSystemInfo();
			if(StringUtils.isNotBlank(systemInfo)){
				systemInfo = systemInfo.replace("&quot;", "\"");
				WxSystemInfo wxSystemInfo = HaiJsonUtils.toBean(systemInfo, WxSystemInfo.class);
				wxModel.setWxSystemInfo(wxSystemInfo);
			}
			
			//3根据code获取session_key
			String url = "https://api.weixin.qq.com/sns/jscode2session";
			Map<String, String> parm = new HashMap<String, String>();
			parm.put("appid", PropertiesUtils.getProperties().getProperty("wx.sale.appId"));
			parm.put("secret", PropertiesUtils.getProperties().getProperty("wx.sale.appSecret"));
			parm.put("grant_type", "authorization_code");
			parm.put("js_code", wxModel.getCode());
			try {
				JSONObject jo = HttpClientUtil.post(url, parm);
				String session_key = jo.getString("session_key");
				if(StringUtils.isBlank(session_key)){
					//获取session_key 失败
					String errcode = jo.getString("errcode");
					String errmsg = jo.getString("errmsg");
					return result.buildIsSuccess(false).buildMsg("errcode:"+errcode+"errmsg:"+errmsg);
				}
				String expires_in = jo.getString("expires_in");
				String openid = jo.getString("openid");
				
				
				//如果是有cookie,则更新缓存cookie的session_key
				String cookieOld = wxModel.getCookie();
				if(StringUtils.isNotEmpty(cookieOld)&&maps.containsKey(cookieOld))
				{
					maps.get(cookieOld).setSessionKey(session_key);
					WxSession wxSession = new WxSession();
					wxSession.setCookie(cookieOld);
					wxSession.setSessionKey(session_key);
					wxSessionService.updateSelectiveById(wxSession);
					return result.buildIsSuccess(true).buildData(cookieOld);
					
				}else{
				
				//4,生成cookie 和 3rd_session (目前cookie=3rd_session)
				String md5Str = wxModel.toString()+session_key+ System.currentTimeMillis();
				String md5Cookie = Md5Util.getMD5(md5Str);
				
				//缓存 cookie 
//				List<String> val = new ArrayList<String>();
//				val.add(session_key);
//				val.add(openid);
				WxSession wxSession = new WxSession();
				wxSession.setCookie(md5Cookie);
				wxSession.setOpenId(openid);
				wxSession.setSessionKey(session_key);
				wxSession.setGmtCreate(new Date());
				maps.put(md5Cookie,wxSession);
				wxSessionService.insert(wxSession);
				//5初始化数据库对象
				device = createDevice(wxModel);
				device.setCookie(md5Cookie);
				deviceService.insert(device);
				return result.buildIsSuccess(true).buildData(md5Cookie);
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return result.buildIsSuccess(false).buildMsg("请求微信服务错误");
			}
			
//成功		{"session_key":"prbkyXyu4vok4WzWl7zH6w==","expires_in":2592000,"openid":"oTFn70JQWcQqZRlwgn8VdqmaedRc"}
//失败		{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: THi00357ns80 ]"}
		}else{
			return result.buildIsSuccess(false).buildMsg("接口错误");
		}
		
	}
	
	
	/**
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/uploadUserInfo")
	@ResponseBody
	public Object uploadUserInfo(UploadUserInfo uploadUserInfo) {
		JsonResult<WxUserVO> result = new JsonResult<>();
		Map<String,WxSession> maps = wxSessionService.getMaps();
		//1、验证cookie
		String cookie = uploadUserInfo.getCookie();
		if(StringUtils.isNotEmpty(cookie)&&maps.containsKey(cookie))
		{
			WxSession wxSession = maps.get(cookie);
			if(wxSession==null){
				maps.remove(wxSession);
				deviceService.deleteById(wxSession);
				return result.buildIsSuccess(false).buildMsg("未登入");
			}
			//2、验签用户
//			wxSession.getSessionKey();
//			wxSession.getOpenId();
			String rowData = uploadUserInfo.getWxRawData().replace("&quot;", "\"");
			String wxRawDataSha1= rowData+wxSession.getSessionKey();
			String wxSha1 = Md5Util.getSha1(wxRawDataSha1);
			if(!wxSha1.equals(uploadUserInfo.getWxSignature())){
				return result.buildIsSuccess(false).buildMsg("验签失败");
			}
			
			//3、解密
		
			
			//4、数据解析
			//4.1先解析rowdata
			WxRowData wxRowData = HaiJsonUtils.toBean(rowData, WxRowData.class);
			//根据openID获取用户，没有的话，需要新增用户，有的话，update
			WxUser wxUserHas = wxUserService.queryWxUser(wxSession.getOpenId());
			//根据cookie获取当前设备
			Device device = deviceService.queryDevice(cookie);
			
			WxUser wxUser = new WxUser();
			
			WxUserVO wxUserVO = new WxUserVO();
			if(wxUserHas==null){
				wxUser.setNickName(wxRowData.getNickName());
				wxUser.setGender(wxRowData.getGender());
				wxUser.setCity(wxRowData.getCity());
				wxUser.setAvatarUrl(wxRowData.getAvatarUrl());
				wxUser.setOpenId(wxSession.getOpenId());
				wxUser.setFirstLoginDevice(device.getId());
				wxUser.setFirstLoginTime(new Date());
				wxUser.setLastLoginDevice(device.getId());
				wxUser.setLastLoginTime(new Date());
				wxUser.setGmtCreate(new Date());
				wxUser.setGmtModify(new Date());
				
				wxUserService.insert(wxUser);
				
				wxUserVO.setUserId(wxUser.getId());
				wxUserVO.setUserNick(wxUser.getNickName());
			}else{
				wxUser.setLastLoginDevice(device.getId());
				wxUser.setLastLoginTime(new Date());
				wxUser.setId(wxUserHas.getId());
				wxUser.setGmtModify(new Date());
				
				wxUserService.updateSelectiveById(wxUser);
				
				wxUserVO.setUserId(wxUserHas.getId());
				wxUserVO.setUserNick(wxUser.getNickName());
			}
			return result.buildIsSuccess(true).buildData(wxUserVO);
		}else{
			return result.buildIsSuccess(false).buildMsg("未登入");
		}
	}

	private Device createDevice(WxModel wxModel) {
		Device device = new Device();
		device.setGmtCreate(new Date());
		device.setGmtModify(new Date());
//		device.setChannelId(wxModel.getWxSystemInfo().get);
		device.setProductId(wxModel.getProductId());
		device.setProductVersion(wxModel.getProductVersion());
		device.setPixelRatio(wxModel.getWxSystemInfo().getPixelRatio());
		device.setWindowWidth(wxModel.getWxSystemInfo().getWindowWidth());
		device.setWindowHeight(wxModel.getWxSystemInfo().getWindowHeight());
		device.setLanguage(wxModel.getWxSystemInfo().getLanguage());
		device.setVersion(wxModel.getWxSystemInfo().getVersion());
		device.setSystem(wxModel.getWxSystemInfo().getVersion());
		device.setPlatform(wxModel.getWxSystemInfo().getPlatform());
		device.setModel(wxModel.getWxSystemInfo().getModel());
		
		return device;
	}
	
	
	@RequestMapping("/refreshCookieCache")
	@ResponseBody
	public Object refreshCookieCache() {
		JsonResult<String> result = new JsonResult<>();
		wxSessionService.refreshCookieCache();
		return result.buildIsSuccess(true);
	}
	
}
